import { sysAjax } from 'Ajax'
import { filterRouter, filterMenu } from '../../utils/filterRouter'
import { getAuthInfo } from '../../../../platform-manage/src/utils/validate'

const state = {
  routesList: [],
  routesMenu: [],
  routesAllMenu: [],
  headerIndex: 0
}
const mutations = {
  SET_HEADER_INDEX: (state, index) => {
    state.headerIndex = index
  },
  SET_ROUTES: (state, routes) => {
    state.routesList = routes
  },
  SET_ROUTES_MUNE: (state, routesIndex) => {
    state.routesMenu = state.routesAllMenu[routesIndex].children
  },
  SET_ROUTES_ALL_MUNE: (state, routes) => {
    state.routesAllMenu = routes
  }
}

const actions = {
  // 设置header 选中状态
  setHeaderIndex({ commit }, index) {
    commit('SET_HEADER_INDEX', index)
  },
  // 设置全部的菜单
  setRoutes({ commit }, list) {
    commit('SET_ROUTES', list)
  },
  // 设置菜单路由
  setRoutesMenu({ commit }, index) {
    commit('SET_ROUTES_MUNE', index)
    commit('SET_HEADER_INDEX', index)
  },
  // 设置所有菜单路由
  setRoutesAllMenu({ commit }, menu) {
    commit('SET_ROUTES_ALL_MUNE', menu)
    commit('SET_ROUTES_MUNE', 0)
  },
  getRoutesMenu({ commit }) {
    return new Promise(resolve => {
      const authInfo = JSON.parse(getAuthInfo())
      // 向后端请求路由数据
      sysAjax.authMenuRouter({ id: authInfo.userId }).then(res => {
        const routerList = filterRouter(res.routerList)
        const menuList = filterMenu(res.menuList)
        commit('SET_ROUTES', routerList)
        commit('SET_ROUTES_ALL_MUNE', menuList)
        commit('SET_ROUTES_MUNE', 0)
        resolve(routerList)
      })
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
